package com.atguigu.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class test_es_04_doc_create {

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));

        //新增文档对象
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("user").id("1001");
        //创建数据库对象
        User user = new User("zhangsan",20,"男");

        ObjectMapper objectMapper = new ObjectMapper();

        String userJson =objectMapper.writeValueAsString(user);

        indexRequest.source(userJson, XContentType.JSON);

        //新增文档、发送请求
        IndexResponse response = esClient.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(response.getIndex());
        System.out.println(response.getId());
        System.out.println(response.getResult());

        //关闭es客户端
        esClient.close();
    }
}
